﻿using System;
using Microsoft.Practices.ServiceLocation;
using Castle.Core.Logging;
using Quartz;
using Quartz.Spi;

namespace Caramel.Quartz.Spi
{
	public class ServiceLocatorJobFactory : IJobFactory
	{
		public ServiceLocatorJobFactory()
		{
			this.Logger = NullLogger.Instance;
		}

		public ILogger Logger { get; set; }

		public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
		{
			try
			{
				return ServiceLocator.Current.GetInstance<IJob>(bundle.JobDetail.Key.Name);
			}
			catch (Exception e)
			{
				this.Logger.ErrorFormat(e, "Could not create instance of job '{0}' - {1}", bundle.JobDetail.Key.Name, e.Message);

				throw;
			}
		}

		public void ReturnJob(IJob job)
		{
			// Do nothing for now...
		}
	}
}
